import {
  EuiButton,
  EuiButtonEmpty,
  EuiCallOut,
  EuiFlexGroup,
  EuiFlexItem,
  EuiModal,
  EuiModalBody,
  EuiModalFooter,
  EuiModalHeader,
  EuiModalHeaderTitle,
} from "@elastic/eui";
import { useMemo, useState } from "react";
import { useUserStore } from "../state/users";
import { useMessageStore } from "../state/messages";
import { formatDateTime } from "./MessageStatus";
import { sizes } from "../styles/sizes";

interface CopyToClipboardModalProps {
  maybeReplyKey: string | null;
  closeModal: () => void;
  vaultId: string;
}

export const CopyToClipboardModal = ({
  maybeReplyKey,
  closeModal,
  vaultId,
}: CopyToClipboardModalProps) => {
  if (!maybeReplyKey) {
    return null;
  }

  const messageStore = useMessageStore();
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo();

  const userAlias = userInfo[maybeReplyKey].alias;
  const userDescription = userInfo[maybeReplyKey].description;
  const userAutogeneratedName = userInfo[maybeReplyKey].displayName;

  const startingLines: string[] = useMemo(() => {
    if (!maybeReplyKey) {
      return [];
    }
    return [
      `VAULT: ${vaultId}`,
      `SOURCE: ${
        userAlias
          ? `${userAlias} (${userAutogeneratedName})`
          : userAutogeneratedName
      }`,
      "", // line of space
      ...(userDescription ? [userDescription] : []),
      "", // line of space
      "======= starts =======",
      "", // line of space
      ...messageStore.messages.reduce((acc, msg) => {
        if (msg.userPk !== maybeReplyKey) {
          return acc;
        }
        const isUserToJournalistMessage =
          msg.type === "userToJournalistMessage";
        const timestamp = formatDateTime(
          isUserToJournalistMessage ? msg.receivedAt : msg.sentAt,
        );
        const prefix = isUserToJournalistMessage ? "SOURCE" : "JOURNALIST";
        return [...acc, `[${timestamp}] ${prefix}:`, msg.message];
      }, [] as string[]),
      "", // line of space
      "======= ends =======",
    ];
  }, [maybeReplyKey]);

  const [workingText, setWorkingText] = useState(startingLines.join("\n"));

  const copyToClipboard = () => {
    navigator.clipboard.writeText(workingText); // TODO handle promise with toasts
    closeModal();
  };

  return (
    <EuiModal
      onClose={closeModal}
      style={{ width: sizes.copyToClipboardModal.width, height: "80vh" }}
    >
      <EuiModalHeader>
        <EuiModalHeaderTitle>Copy to clipboard</EuiModalHeaderTitle>
      </EuiModalHeader>
      <EuiModalBody>
        <EuiFlexGroup direction="column" style={{ height: "100%" }}>
          <EuiFlexItem grow={false}>
            <EuiCallOut
              title="Proceed with caution!"
              color="warning"
              iconType="warning"
            >
              The following text may contain sensitive information and should
              only be shared through secure channels. You can edit the text
              before copying it.
            </EuiCallOut>
          </EuiFlexItem>
          <EuiFlexItem grow={true}>
            <textarea
              value={workingText}
              onChange={(e) => setWorkingText(e.target.value)}
              style={{
                height: "100%",
                resize: "none",
                width: "100%",
                padding: "5px",
              }}
            ></textarea>
          </EuiFlexItem>
        </EuiFlexGroup>
      </EuiModalBody>
      <EuiModalFooter>
        <EuiButtonEmpty onClick={closeModal}>Cancel</EuiButtonEmpty>
        <EuiButton fill onClick={copyToClipboard}>
          Copy to Clipboard
        </EuiButton>
      </EuiModalFooter>
    </EuiModal>
  );
};
